#include <fstream>
#include <iostream>
#include <filesystem>
#include <string>
#include <fmt/format.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

int main()
{
    std::string path;
    std::cout<<"请输入旧版CCS文件路径: ";
    std::cin>>path;
    std::cout<<"文件路径为: "<<path<<std::endl;
    std::string filename=path.substr(path.find_last_of('/')+1,path.find_last_of('.')-1);
    if(filename.empty())
    {
        std::cerr<<"文件名格式错误"<<std::endl;
        return 0;
    }
    std::string outputPath=path.substr(0,path.find_last_of('.'));
    std::cout<<"数据输出路径: "<<outputPath<<std::endl;
    std::filesystem::create_directory(outputPath);
    std::filesystem::exists(path);
    std::ifstream iFile;
    iFile.open(path,std::ios_base::binary);
    iFile.seekg(0,std::ios_base::beg);
    int32_t imageCount,imageWidth,imageHeight;
    iFile.read((char*)&imageCount,sizeof(imageCount));
    iFile.read((char*)&imageWidth,sizeof(imageWidth));
    iFile.read((char*)&imageHeight,sizeof(imageHeight));
    unsigned char* imageData=new unsigned char[imageHeight*imageWidth];
    for(int i=0;i<imageCount;i++)
    {
        iFile.read((char*)imageData,imageWidth*imageHeight);
        stbi_write_bmp(fmt::format("{}/{}.bmp",outputPath,i).c_str(),imageWidth,imageHeight,1,imageData);
        if(!iFile.good())
        {
            std::cerr<<"意外终止的文件流，已处理数: "<<i<<std::endl;
            delete[] imageData;
            return 0;
        }
    }
    std::cout<<"文件已全部处理完毕!"<<std::endl;
    delete[] imageData;
}